import { apiTree, resSaveApi, resApiList, ResApiDetail } from '../services';
import { ResTree } from '@/pages/BaseManage/ResourceManage/entity';
import { Box, Button, Dialog, Divider, Field, Form, Icon, Input, Message, Table, Tree } from '@alifd/next';
import { useEffect, useState } from 'react';
import { useRequest } from 'ice';

interface Props {
  visible?: boolean;
  onClose?: () => any;
  privilegeId: number;
}

function ResWarrantDialog({ visible, onClose, privilegeId }: Props) {
  const form = Field.useField([{}]);
  const { data: tree } = useRequest<any, ResTree[]>(apiTree, { manual: false });
  const {
    loading,
    request,
    data = [],
    mutate,
  } = useRequest<ResApiDetail[], Array<number | undefined>>(resApiList, {
    initialData: [],
    defaultLoading: true,
    defaultParams: [],
  });
  const { request: edit } = useRequest(resSaveApi, {
    manual: true,
    onSuccess: (_r, _) => {
      Message.success('操作成功');
      onClose?.();
    },
  });

  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [apiVisible, setApiVisible] = useState<boolean>(false);
  const [resApiArr, setResApiArr] = useState<ResApiDetail[]>([]);

  useEffect(() => {
    if (visible) {
      request(privilegeId);
    }
  }, [visible]);

  const onSubmit = () => {
    form.validateCallback((errors: any[], values: any) => {
      if (errors) {
        return;
      }
      const path = values?.path || '';
      const _data = data || [];
      const _index = _data.findIndex((t) => t.path == path);
      if (_index >= 0) {
        _data[_index] = values;
      } else {
        _data.push(values);
      }
      mutate([..._data]);
      setEditVisible(false);
    });
  };

  const openEditDialog = (_row: ResApiDetail) => {
    setEditVisible(true);
    form.setValues({ ..._row, privilegeId });
  };

  const onCheck = (_, extra) => {
    const checkArr = extra.checkedNodes || [];
    const de = checkArr.map((p) => p.props).map((t) => ({ path: t.path, method: t.method }));
    setResApiArr(de);
  };

  return (
    <Dialog
      title="资源授权"
      v2
      visible={visible}
      overflowScroll
      width="60%"
      onOk={() => edit({ privilegeId, uriList: data })}
      onClose={onClose}
    >
      <Box direction="row" justify="flex-end" align="center" margin={[0, 0, 10, 0]}>
        <Button
          type="primary"
          onClick={() => {
            setApiVisible(true);
            setResApiArr(data);
          }}
        >
          <Icon type="add" /> 新增
        </Button>
      </Box>
      <Table dataSource={data} maxBodyHeight={400} useVirtual loading={loading}>
        <Table.Column dataIndex="path" title="接口路径" asyncResizable />
        <Table.Column dataIndex="method" title="接口方法" asyncResizable />
        <Table.Column
          dataIndex="shippingId"
          title="操作"
          cell={(val, i, _row) => (
            <>
              <Button
                type="primary"
                text
                onClick={() => {
                  const _data = data || [];
                  const _index = _data.findIndex((t) => t.path == _row.path);
                  if (_index >= 0) {
                    _data.splice(_index, 1);
                  }
                  mutate([..._data]);
                }}
              >
                删除
              </Button>
              <Divider direction="ver" />
              <Button type="primary" text onClick={() => openEditDialog(_row)}>
                编辑
              </Button>
            </>
          )}
        />
      </Table>

      <Dialog
        title="编辑"
        v2
        visible={editVisible}
        overflowScroll
        width="60%"
        onClose={() => setEditVisible(false)}
        onOk={onSubmit}
        afterClose={() => form.reset()}
      >
        <Form colon field={form} useLabelForErrorMessage>
          <Form.Item label="privilegeId" name="privilegeId" disabled>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="接口路径" name="path" required>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="接口方法" name="method" required>
            <Input placeholder="请输入" />
          </Form.Item>
        </Form>
      </Dialog>

      <Dialog
        title="接口授权"
        v2
        visible={apiVisible}
        overflowScroll
        width="60%"
        onClose={() => setApiVisible(false)}
        afterClose={() => setResApiArr([])}
        onOk={() => {
          mutate(resApiArr);
          setApiVisible(false);
        }}
      >
        <Tree
          checkable
          showLine
          checkedKeys={resApiArr.map((t) => t.path)}
          checkedStrategy="child"
          selectable={false}
          defaultCheckedKeys={[]}
          onCheck={onCheck}
          dataSource={tree}
        />
      </Dialog>
    </Dialog>
  );
}

export default ResWarrantDialog;
